package bancosys.tec.services.input.driver.processor;

import java.util.List;

import jmine.tec.services.io.ServiceBean;
import jmine.tec.services.io.ServicesPageBean;

import org.apache.log4j.Logger;

import bancosys.tec.datadigester.DigesterBean;
import bancosys.tec.datadigester.processor.AbstractProcessor;
import bancosys.tec.datadigester.processor.Processor;
import bancosys.tec.services.input.driver.bean.ServicePageHeader;

/**
 * Abstract class for processors that execute services.
 * 
 * @author lundberg
 * @param <B>
 */
public abstract class AbstractServiceProcessor<B extends DigesterBean> extends AbstractProcessor {

    private static final Logger LOG = Logger.getLogger(AbstractServiceProcessor.class);

    private Processor serviceProcessor;

    /**
     * Processes the digester bean.
     * 
     * @param digesterBean digesterBean
     */
    @Override
    @SuppressWarnings("unchecked")
    public final void doProcess(DigesterBean digesterBean) {
        ServicePageHeader header = new ServicePageHeader();
        LOG.debug("Processando arquivo em " + this.getClass().getSimpleName());
        for (ServicesPageBean page : this.createServicePages((B) digesterBean)) {
            header.addSheet(page);
        }
        LOG.debug("Páginas de serviço criadas: " + header.getWorkSheets().size());
        this.getServiceProcessor().process(header);
    }

    /**
     * Returns a list of service pages as a result of processing the digesterBean
     * 
     * @param digesterBean digesterBean
     * @return List of ServicesPageBean
     */
    protected abstract List<ServicesPageBean> createServicePages(B digesterBean);

    /**
     * @return the serviceProcessor
     */
    public Processor getServiceProcessor() {
        return this.serviceProcessor;
    }

    /**
     * @param serviceProcessor the serviceProcessor to set
     */
    public void setServiceProcessor(Processor serviceProcessor) {
        this.serviceProcessor = serviceProcessor;
    }

    /**
     * Helper method, creates a ServicesPageBean containing the given serviceBeans
     * 
     * @param serviceBeans List of ServiceBean
     * @return ServicesPageBean containing the serviceBeans
     */
    protected ServicesPageBean createPage(List<ServiceBean> serviceBeans) {
        ServicesPageBean page = new ServicesPageBean();
        for (ServiceBean bean : serviceBeans) {
            page.addService(bean);
        }
        return page;
    }
}
